// BOM管理主页面
<script setup lang="ts">
// 导入BOM表单子组件
import BomForm from './components/BomForm.vue'

// 导入所需的Vue组件和工具函数
import {nextTick, onMounted, onUnmounted, reactive, ref} from "vue";
import {ElMessage, FormInstance} from "element-plus";

// 导入BOM相关的类型定义和API
import {Bom, BomListParam} from "@/api/bom/type";
import {addApi,deleteApi, getListApi, getBomDetailByIdApi,getBomStructure} from "@/api/bom";
// 导入图标组件
import {Search, Refresh, Plus, Edit, Delete} from '@element-plus/icons-vue'

import SysDialog from "@/components/dialog/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import useInstance from "@/hooks/useInstance";
// 使用dialog钩子获取弹窗控制方法
const {dialog, onShow, onClose} = useDialog()
const {global} = useInstance()

// 定义表格高度，用于自适应布局
const tableHeight = ref(0)

// 表格数据相关的响应式变量
const tableData = ref([]) // 表格数据
const loading = ref(false) // 加载状态
// 分页相关数据
const paginationData = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

// 查询表单对象
const searchForm = reactive<BomListParam>({
  bomCode: undefined,    // BOM编码
  bomName: undefined,    // BOM名称
  isActive: undefined,   // 启用状态
  page: 1,              // 当前页
  limit: 10             // 每页条数
})

// 查询方法 - 重置页码并获取数据
const search = () => {
  paginationData.currentPage = 1
  getTableData()
}

// 重置查询条件
const reset = () => {
  searchForm.bomCode = undefined
  searchForm.bomName = undefined
  searchForm.isActive = undefined
  search()
}

// 获取表格数据的核心方法
const getTableData = async () => {
  loading.value = true
  try {
    // 设置分页参数
    searchForm.page = paginationData.currentPage
    searchForm.limit = paginationData.pageSize
    // 调用API获取数据
    let res = await getListApi(searchForm)
    if (res && res.data) {
      tableData.value = res.data.list
      paginationData.total = res.data.total
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 删除BOM记录
const deleteOne = async (id: number) => {
  // 删除确认
  const confirm = await global.$myConfirm('确定要删除该BOM吗？')
  if (confirm) {
    try {
      await deleteApi(id)
      ElMessage.success('删除成功')
      // 如果当前页只有一条数据，删除后自动跳转到上一页
      if (tableData.value.length === 1 && paginationData.currentPage > 1) {
        paginationData.currentPage--
      }
      getTableData()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }
}

// 生命周期钩子 - 组件挂载时初始化数据和设置表格高度
onMounted(() => {
  getTableData()
  nextTick(() => {
    tableHeight.value = window.innerHeight - 268
  })
})

// 监听窗口大小变化，动态调整表格高度
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
}

// 组件挂载时添加窗口大小变化监听
onMounted(() => {
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除监听器
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// BOM表单显示控制
const showForm = ref(false)                    // 控制表单显示/隐藏
const formMode = ref<string>('add')           // 表单模式：add/edit/view
const currentBomId = ref<number>()            // 当前操作的BOM ID

// 新增BOM
const handleAdd = () => {
  formMode.value = 'add'
  currentBomId.value = undefined
  showForm.value = true
}

// 编辑BOM
const handleEdit = (row: Bom) => {
  formMode.value = 'edit'
  currentBomId.value = row.id
  showForm.value = true
}

// 查看BOM详情
const handleView = (row: Bom) => {
  formMode.value = 'view'
  currentBomId.value = row.id
  showForm.value = true
}

// 保存成功后的回调
const handleSaveSuccess = () => {
  showForm.value = false
  getTableData()
}

// 取消操作
const handleCancel = () => {
  showForm.value = false
}

// 导入BOM结构弹窗组件
import BomStructureDialog from './components/BomStructureDialog.vue'

// BOM结构弹窗引用
const bomStructureDialogRef = ref()

// 查看BOM结构
const handleViewStructure = (row: Bom) => {
  bomStructureDialogRef.value.show(row.bomCode)
}
</script>

<template>
    <!-- 左侧列表 -->
    <el-main v-if="!showForm">
      <el-card class="search-card">
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="searchForm" >
          <el-form-item label="BOM编码">
            <el-input v-model="searchForm.bomCode" placeholder="请输入BOM编码"/>
          </el-form-item>
          <el-form-item label="BOM名称">
            <el-input v-model="searchForm.bomName" placeholder="请输入BOM名称"/>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.isActive" placeholder="是否启用" clearable filterable style="width: 110px">
              <el-option label="启用" :value="0"/>
              <el-option label="禁用" :value="1"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search">
              <el-icon><Search/></el-icon>
              查询
            </el-button>
            <el-button @click="reset">
              <el-icon><Refresh/></el-icon>
              重置
            </el-button>
            <el-button type="success" @click="handleAdd">
              <el-icon><Plus/></el-icon>
              新增
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 表格 -->
      <el-table
          v-loading="loading"
          :data="tableData"
          border
          :height="tableHeight"
          style="width: 100%;margin-top: 15px"
      >
        <el-table-column type="index" label="序号" width="70"/>
        <el-table-column prop="bomCode" label="BOM编码" min-width="120"/>
        <el-table-column prop="bomName" label="BOM名称" min-width="120"/>
        <el-table-column prop="specification" label="规格" min-width="200" />
        <el-table-column prop="brand" label="品牌" min-width="100" />
        <el-table-column prop="manufacturer" label="生产厂家" min-width="150" />
        <el-table-column prop="materialType" label="材质" min-width="100" />
        <el-table-column prop="unitWeight" label="米重(kg/m)" min-width="100" />
        <el-table-column prop="unitArea" label="面积(m²/m)" min-width="100" />
        <el-table-column prop="totalWeight" label="总重(kg/件)" min-width="100" />
        <el-table-column prop="thickness" label="厚度(mm)" min-width="100" />
        <el-table-column prop="materialTotalPrices" label="物料总价" min-width="120"/>
        <el-table-column prop="processTotalPrices" label="工序总价" min-width="120"/>
        <el-table-column prop="totalPrices" label="总价" min-width="120"/>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip/>
        <el-table-column prop="isActive" label="状态" min-width="80">
          <template #default="scope">
            <el-tag :type="scope.row.isActive === 0 ? 'primary' : 'danger'" effect="dark">
              {{ scope.row.isActive === 0 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button type="success" size="small" link @click="handleEdit(scope.row)" icon="Edit">编辑</el-button>
            <el-button type="primary" size="small" link @click="handleView(scope.row)" icon="View">详情</el-button>
            <el-button type="warning" size="small" link @click="handleViewStructure(scope.row)" icon="View">结构</el-button>
            <el-button type="danger" size="small" link @click="deleteOne(scope.row.id)" icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-model:current-page="paginationData.currentPage"
          v-model:page-size="paginationData.pageSize"
          :page-sizes="[10, 20, 50]"
          :total="paginationData.total"
          layout="total, sizes, prev, pager, next"
          class="pagination"
          @size-change="getTableData"
          @current-change="getTableData"
      />
    </el-main>

    <!-- 右侧表单占满整个屏幕 -->
    <el-main v-else>
      <BomForm
          :bom-id="currentBomId"
          :mode="formMode"
          @save-success="handleSaveSuccess"
          @cancel="handleCancel"
      />
    </el-main>

    <!-- 添加BOM结构弹窗组件 -->
    <bom-structure-dialog ref="bomStructureDialogRef"/>
</template>


<style scoped lang="scss">
.el-pagination {
  margin-top: 10px;
  justify-content: flex-end;
}

.search-card {
  height: 70px;
}
</style>
